package org.jim.server.command.handler;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.ImAio;
import org.jim.common.ImConst;
import org.jim.common.ImPacket;
import org.jim.common.ImStatus;
import org.jim.common.cache.redis.JedisTemplate;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.message.MessageHelper;
import org.jim.common.packets.*;
import org.jim.common.utils.ChatKit;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.command.handler.processor.chat.MsgQueueRunnable;
import org.tio.core.ChannelContext;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 功能说明: 获取历史群聊审核消息处理器
 *
 * @author : Alex 创建时间: 2019年10月12日 下午7:00:40
 */
public class ChatCheckHisReqHandler extends AbstractCmdHandler {

    RedisCache checkChatCache = new RedisCache(ImConst.CHECKCHAT, -1, -1);

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {
        MessageReqBody messageReqBody = null;
        try {
            messageReqBody = JsonKit.toBean(packet.getBody(), MessageReqBody.class);
        } catch (Exception e) {
            //用户消息格式不正确
            return getMessageFailedPacket(channelContext);
        }
        //群组ID;
        String groupId = messageReqBody.getGroupId();
        //当前用户ID;
        String userId = messageReqBody.getUserId();
        //分页偏移量;
        Integer offset = messageReqBody.getOffset();
        //分页数量;
        Integer count = messageReqBody.getCount();
        //消息类型;
//        int type = messageReqBody.getType();
        UserMessageData messageData = this.getChatCheckHistoryMessage(userId, groupId, offset, count);
        RespBody resPacket = new RespBody(Command.COMMAND_CHATCHECKHIS_RESP, ImStatus.C10033);
        resPacket.setData(messageData);
        return ImKit.ConvertRespPacket(resPacket, channelContext);
    }

    public UserMessageData getChatCheckHistoryMessage(String userid, String groupid, Integer offset, Integer count) throws Exception {
        MessageHelper messageHelper = imConfig.getMessageHelper();
        UserMessageData messageData = messageHelper.getGroupChatcheckHis(userid, groupid, null, null, offset, count);
        return messageData;
    }

    /**
     * 获取用户消息失败响应包;
     *
     * @param channelContext
     * @return
     */
    public ImPacket getMessageFailedPacket(ChannelContext channelContext) {
        RespBody resPacket = new RespBody(Command.COMMAND_CHATCHECKHIS_RESP, ImStatus.C10022);
        return ImKit.ConvertRespPacket(resPacket, channelContext);
    }

    @Override
    public Command command() {
        return Command.COMMAND_CHATCHECKHIS_REQ; // 44:获取历史群聊审核消息请求
    }
}
